Программирование сетевых приложений
Коммуникация между потоками в Qt (сигналы и слоты)
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <QTimer>
class Worker : public QObject {
Q_OBJECT
private:
int counter;
public:
Worker() : counter(0) {}
public slots:
void process() {
++counter;
emit progress(counter);
if (counter >= 10) {
emit finished();
} else {
QTimer::singleShot(1000, this, &Worker::process);
}
}
signals:
void progress(int value);
void finished();
};
class Controller : public QObject {
Q_OBJECT
private:
Worker* worker;
QThread* workerThread;
public:
Controller() {
worker = new Worker;
workerThread = new QThread(this);
worker->moveToThread(workerThread);
connect(workerThread, &QThread::started, worker, &Worker::process);
connect(worker, &Worker::progress, this, &Controller::onProgress);
connect(worker, &Worker::finished, this, &Controller::onFinished);
connect(worker, &Worker::finished, workerThread, &QThread::quit);
connect(workerThread, &QThread::finished, worker, &Worker::deleteLater);
connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater);
workerThread->start();
}
public slots:
void onProgress(int value) {
qDebug() << "Прогресс:" << value;
}
void onFinished() {
qDebug() << "Работа завершена";
QCoreApplication::quit();
}
};